package com.us.usws.support.uitls.factory;

import net.iwsh.core.exception.GenericRuntimeException;

/**
 * Object builder
 * @author Wang Jianbo
 */
public class ObjectBuilder {

	private ObjectBuilder() {
	}

	public static Object newObject(String className) {
		try {
			Class<?> cls = loadClass(className);
			return cls.newInstance();
		} catch (Exception e) {
			throw new GenericRuntimeException(e.getMessage());
		}
	}

	public static <T> T newObject(Class<T> cls) {
		try {
			return cls.newInstance();
		} catch (Exception e) {
			throw new GenericRuntimeException(e.getMessage());
		}
	}

	public static Class<?> loadClass(String className) {
		try {
			return loadClass(className, null);
		} catch (ClassNotFoundException e) {
			throw new IllegalArgumentException("Class '" + className + "' could not be found: " + e.getMessage());
		}
	}

	public static Class<?> loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException {
		if (classLoader == null) {
			// Look up the class loader to be used
			classLoader = Thread.currentThread().getContextClassLoader();

			if (classLoader == null) {
				classLoader = ObjectBuilder.class.getClassLoader();
			}
		}
		// Attempt to load the specified class
		return classLoader.loadClass(className);
	}
}
